package com.dropdb.demo.controller.admin;

import com.dropdb.demo.bean.Admin;
import com.dropdb.demo.bean.bo.AdminAdminListBO;
import com.dropdb.demo.bean.vo.AdminData;
import com.dropdb.demo.bean.vo.BaseRespVO;
import com.dropdb.demo.service.AdminService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("admin/admin")
public class AdminAdminController {

    @Autowired
    AdminService adminService;

    @GetMapping("list")
    @RequiresPermissions(value = {"*", "admin:admin:list"}, logical = Logical.OR)
    public BaseRespVO list(@Valid AdminAdminListBO adminAdminListBO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return BaseRespVO.error(502, bindingResult.getFieldError().getDefaultMessage());
        }
        return BaseRespVO.ok(adminService.list(adminAdminListBO));
    }

    @PostMapping("create")
    @RequiresPermissions(value = {"*", "admin:admin:create"}, logical = Logical.OR)
    public BaseRespVO create(@RequestBody Admin admin) {
        if (null == admin.getUsername() || admin.getUsername().length() < 6 || admin.getUsername().length() > 20) {
            return BaseRespVO.error(601, "管理员名称不符合规定");
        }
        if (null == admin.getPassword() || admin.getPassword().length() < 6) {
            return BaseRespVO.error(602, "管理员密码长度不能小于6");
        }
        AdminData adminFromDb = adminService.create(admin);
        if (null == adminFromDb) {
            return BaseRespVO.error(602, "管理员已经存在");
        }
        return BaseRespVO.ok(adminFromDb);
    }

    @PostMapping("update")
    @RequiresPermissions(value = {"*", "admin:admin:update"}, logical = Logical.OR)
    public BaseRespVO update(@RequestBody Admin admin) {
        if (null == admin.getUsername() || admin.getUsername().length() < 6 || admin.getUsername().length() > 20) {
            return BaseRespVO.error(601, "管理员名称不符合规定");
        }
        if (null == admin.getPassword() || admin.getPassword().length() < 6) {
            return BaseRespVO.error(602, "管理员密码长度不能小于6");
        }
        AdminData adminFromDb = adminService.update(admin);
        return null != adminFromDb ? BaseRespVO.ok(adminFromDb) : BaseRespVO.error(602, "管理员已经存在");
    }

    @PostMapping("delete")
    @RequiresPermissions(value = {"*", "admin:admin:delete"}, logical = Logical.OR)
    public BaseRespVO delete(@RequestBody Admin admin) {
        int result = adminService.delete(admin);
        return 1 == result ? BaseRespVO.ok() : BaseRespVO.error(502, "系统内部错误");
    }
}
